﻿using CommonBase;
using CommonClass;
using EnvControlLib;
using FileLib;
using Microsoft.Practices.Prism.Commands;
using SurveillanceLib;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace ToolkitMgtModule.ViewModels
{
    /// <summary>
    /// 文件下载
    /// </summary>
    public class ViewModel_DownloadFile : WorkspaceViewModel
    {
        #region Const Fields

        private readonly string SAVEPATH_DOWNLOADVIDEO;

        #endregion

        #region Private Fields

        private string _pDownloadHandleByRecordFile; // 文件下载结果状态
        private string _saveDownloadVideoFileName; // 保存的下载远程录像回放文件名
        private bool _isDownloading; // 表示是否正在下载远程录像回放文件
        private FileDetailModel _currentDownloadingFile;
        private DelegateCommand _cmdStopDownload;

        #endregion

        #region Constructor

        public ViewModel_DownloadFile()
        {
            base.ViewName = SurveillancePro.Base.Common.ViewNames.ToolkitMgtModule_DownloadFile;
            base.HeaderTitle = "文件下载";
            base.HeaderImageSource = string.Format(ConstantString.IMAGE_URL, "Question");
            base.IsShowCloseButton = Visibility.Collapsed;

            this._isDownloading = false; // 未下载
            if (string.IsNullOrWhiteSpace(SurveillanceUtilities.DownloadVideoPath))
                SAVEPATH_DOWNLOADVIDEO = SurveillanceUtilities.USERCONFIG_DOWNLOADVIDEOPATH_DEFAULT;
            else
                SAVEPATH_DOWNLOADVIDEO = SurveillanceUtilities.DownloadVideoPath;

            this._downloadVideoPath = this.SAVEPATH_DOWNLOADVIDEO;
            FileOperation.CreatDirectory(SAVEPATH_DOWNLOADVIDEO); // 创建文件夹

            DownloadFileList = new ObservableCollection<FileDetailModel>();
            DownloadFileList.CollectionChanged += OnCollectionChanged;
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Event Handling Methods

        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems.Count != 0)
                foreach (FileDetailModel file in e.NewItems)
                    file.PropertyChanged += this.OnFileDetailModelPopertyChanged;

            if (e.OldItems != null && e.OldItems.Count != 0)
                foreach (FileDetailModel file in e.OldItems)
                    file.PropertyChanged -= this.OnFileDetailModelPopertyChanged;
        }

        void OnFileDetailModelPopertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // Blank for now
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// 文件下载列表
        /// </summary>
        public ObservableCollection<FileDetailModel> DownloadFileList { get; private set; }

        private string _downloadVideoPath;
        /// <summary>
        /// 文件下载路径
        /// </summary>
        public string DownloadVideoPath
        {
            get
            {
                return _downloadVideoPath;
            }
            set
            {
                if (_downloadVideoPath == value) return;
                _downloadVideoPath = value;
                base.OnPropertyChanged("DownloadVideoPath");
            }
        }

        private bool? _isSelectAll = false; // 初值：表示不“全选”
        /// <summary>
        /// CheckBox 是否全选
        /// <para>三态</para>
        /// </summary>
        public bool? IsSelectAll
        {
            get
            {
                return _isSelectAll;
            }
            set
            {
                _isSelectAll = value;
                base.OnPropertyChanged("IsSelectAll");


                if (DownloadFileList != null)
                {
                    foreach (FileDetailModel file in DownloadFileList)
                    {
                        if (value.HasValue)
                            file.IsSelected = value.Value;
                    }
                }
            }
        }


        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_StopDownloadFileList
        {
            get
            {
                if (_cmdStopDownload == null)
                {
                    _cmdStopDownload = new DelegateCommand(_stopDownloadFileList, _canStopDownloadFileList);
                }
                return _cmdStopDownload;
            }
        }

        /// <summary>
        /// 列表单个项目选择时
        /// </summary>
        public ICommand Cmd_DataGridClickCheckBox
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    IsSelectAll = Utilities.SetSelectAllCheckBoxState(DownloadFileList);
                });
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 将所选文件添加到下载列表中
        /// </summary>
        /// <param name="selectedFileList">所选文件列表</param>
        public void Add2List(List<FileDetailModel> selectedFileList)
        {
            try
            {
                if (selectedFileList == null ||
                    selectedFileList.Count <= 0)
                    return;

                FileDetailModel downloadFile;
                // 去重复文件
                foreach (FileDetailModel file in selectedFileList)
                {
                    if (DownloadFileList.IndexOf(file) < 0) // 未找到已存在的项时
                    {
                        downloadFile = new FileDetailModel(file.NetRecordFileInfo);
                        Utilities.CopyObject(file, downloadFile);

                        DownloadFileList.Add(downloadFile);
                    }
                }

                base.OnPropertyChanged("DownloadFileList");
                IsSelectAll = false; // 不全选
                _downloadFirstFile(); // 文件列表改变时，判断是否需要继续下载文件
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canStopDownloadFileList()
        {
            return true;
        }


        /// <summary>
        /// 停止下载
        /// </summary>
        private void _stopDownloadFileList()
        {
            try
            {
                List<FileDetailModel> _selectedDownloadFileList; // 所选下载文件列表
                if (DownloadFileList != null && DownloadFileList.Count > 0)
                {
                    _selectedDownloadFileList = DownloadFileList.Where(c => c.IsSelected).ToList(); // 获得所选下载文件列表

                    if (_selectedDownloadFileList.Count <= 0)
                    {
                        AutoCloseNoticeWindow.Show("请选择要停止下载的文件！");
                        return;
                    }
                    else
                    {
                        if (_selectedDownloadFileList.IndexOf(_currentDownloadingFile) >= 0) // 要停止的文件中包含正在下载的文件
                        {
                            _stopDownload(); // 停止下载
                        }

                        foreach (FileDetailModel stopFile in _selectedDownloadFileList)
                        {
                            DownloadFileList.Remove(stopFile);
                        }
                    }

                    _downloadFirstFile(); // 文件列表改变时，判断是否需要继续下载文件
                }
                else
                    AutoCloseNoticeWindow.Show("请选择要停止下载的文件！");
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region 回调函数
        /// <summary>
        /// 进度回调函数
        /// </summary>
        /// <param name="lPlayHandle">播放句柄:CLIENT_PlayBackByRecordFile返回值</param>
        /// <param name="dwTotalSize">指本次播放总大小，单位为KB</param>
        /// <param name="dwDownLoadSize">指已经播放的大小，单位为KB，当其值为-1时表示本次回防结束</param>
        /// <param name="dwUser">用户数据</param>
        private void _fDownLoadPosCallBack(int lPlayHandle, uint dwTotalSize,
            uint dwDownLoadSize, IntPtr dwUser)
        {
            try
            {
                if (_currentDownloadingFile != null)
                {
                    if (dwDownLoadSize > dwTotalSize)
                    {
                        if (dwDownLoadSize == uint.MaxValue) // 表示下载完成
                        {
                            Application.Current.Dispatcher.Invoke((Action)(() =>
                            {
                                DownloadFileList.Remove(_currentDownloadingFile); // 已下载完成，并移除首个文件
                            }));

                            dwDownLoadSize = 0; // 进度重置
                            _stopDownload(); // 停止下载，否则继续下载失败
                            _downloadFirstFile(); // 文件列表改变时，判断是否需要继续下载文件
                        }
                        else
                            dwDownLoadSize = dwTotalSize; // 防止显示超过 100%
                    }

                    _currentDownloadingFile.Percentage = string.Format("{0:f2} %",
                        100.00 * dwDownLoadSize / dwTotalSize); // 计算进度百分比
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }
        #endregion

        /// <summary>
        /// 开始下载
        /// </summary>
        private void _startDownload()
        {
            this._isDownloading = false; // 未下载

            try
            {
                if (_currentDownloadingFile == null)
                    return;

                if (_currentDownloadingFile.SelectedDriver != null &&
                    _currentDownloadingFile.SelectedDriver.Driver_Instance != null &&
                    !string.IsNullOrWhiteSpace(_currentDownloadingFile.SelectedDriver.Driver_LoginID))
                {
                    TagModel driverTag = _currentDownloadingFile.SelectedDriver;
                    _saveDownloadVideoFileName = Path.Combine(SAVEPATH_DOWNLOADVIDEO,
                        string.Format("DownloadVideo_{0}_{1}_{2}_{3}.dav", _currentDownloadingFile.DriverIP,
                        _currentDownloadingFile.DriverChannel,
                        _currentDownloadingFile.FileStartTime.ToString("yyyyMMddHHmmss"),
                        _currentDownloadingFile.FileEndTime.ToString("yyyyMMddHHmmss"))); // 保存的文件名称
                    _pDownloadHandleByRecordFile = driverTag.Driver_Instance.DownloadByRecordFile(
                        driverTag.Driver_LoginID,
                        _currentDownloadingFile.NetRecordFileInfo, _saveDownloadVideoFileName,
                        _fDownLoadPosCallBack, IntPtr.Zero); // 按文件下载录像文件

                    if (!string.IsNullOrWhiteSpace(_pDownloadHandleByRecordFile))
                    {
#if DEBUG
                        Debug.WriteLine("开始下载远程录像回放文件");
#endif
                        this._isDownloading = true; // 下载中
                        DownloadVideoPath = _saveDownloadVideoFileName;
                    }
                    else
                    {
#if DEBUG
                        Debug.WriteLine("下载失败！");
#endif
                        MessageBox.Show("下载失败！", ConstantString.MSG_COMPANY);
                    }
                }
                else
                {
                    MessageBox.Show("开始下载文件失败！", ConstantString.MSG_COMPANY);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 停止下载
        /// </summary>
        private void _stopDownload()
        {
            try
            {
                if (_currentDownloadingFile == null)
                    return;

                if (!string.IsNullOrWhiteSpace(_pDownloadHandleByRecordFile) &&
                    _currentDownloadingFile.SelectedDriver != null &&
                    _currentDownloadingFile.SelectedDriver.Driver_Instance != null)
                {
                    TagModel driverTag = _currentDownloadingFile.SelectedDriver;
                    bool pStopDownloadHandle = driverTag.Driver_Instance.StopDownload(
                        _pDownloadHandleByRecordFile); // 停止下载录像文件

                    if (pStopDownloadHandle)
                    {
#if DEBUG
                        Debug.WriteLine("停止下载远程录像回放文件成功");
#endif
                    }
                    else
                    {
#if DEBUG
                        Debug.WriteLine("下载文件保存失败！");
#endif
                        MessageBox.Show("下载文件保存失败！", ConstantString.MSG_COMPANY);
                    }
                }
                else
                {
                    MessageBox.Show("停止下载文件失败！", ConstantString.MSG_COMPANY);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            this._isDownloading = false; // 未下载
        }

        /// <summary>
        /// 判断是否继续下载文件
        /// </summary>
        private void _downloadFirstFile()
        {
            if (!this._isDownloading && DownloadFileList.Count > 0) // 未下载
            {
                _currentDownloadingFile = DownloadFileList.FirstOrDefault();
                _startDownload(); // 开始下载列表第一个文件
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            try
            {
                if (this._isDownloading && _currentDownloadingFile != null) // 正在下载中
                {
                    if (!string.IsNullOrWhiteSpace(_pDownloadHandleByRecordFile) &&
                        _currentDownloadingFile.SelectedDriver != null &&
                        _currentDownloadingFile.SelectedDriver.Driver_Instance != null)
                    {
                        TagModel driverTag = _currentDownloadingFile.SelectedDriver;
                        bool pStopDownloadHandle = driverTag.Driver_Instance.StopDownload(
                            _pDownloadHandleByRecordFile); // 停止下载录像文件

                        if (pStopDownloadHandle)
                        {
#if DEBUG
                            Debug.WriteLine("停止下载远程录像回放文件成功");
#endif
                        }
                        else
                        {
#if DEBUG
                            Debug.WriteLine("下载文件保存失败！");
#endif
                        }
                    }
                }

                if (DownloadFileList != null)
                {
                    DownloadFileList.Clear();
                    DownloadFileList.CollectionChanged -= this.OnCollectionChanged;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion
    }
}
